<template>
    <div class="echarts-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onUnmounted, inject, nextTick } from 'vue';
import { formatDate, formatToHundredMillion, getDateRange } from '@/utils/utils'
import { useStockDetailStore } from '@/stores/stock';

// 注入 echarts
const echarts = inject('echarts');
// 获取DOM引用
// const isAllScreen = computed(() => props.isAllScreen)
// 导出一个方法供父组件调用
defineExpose({
    refreshChart() {
        if (chartInstance) {
            nextTick().then(() => {
                chartInstance.resize();
            })
        }
    }
});
const chartRef = ref(null);
const { getKlineDataRef, getKlineData, getStockDetailRef } = useStockDetailStore();
const dataZoomStart = ref(20);
const dataZoomEnd = ref(90);
const kLineDayAdd = ref(10);
const klineData = computed(() => {
    const dataCopy = getKlineDataRef();
    const categoryData = [];
    const klineValues = [];
    const volumeValues = [];
    for (let index = 0; index < dataCopy.length; index++) {
        const element = dataCopy[index];
        categoryData.push(formatDate(new Date(element['日期'])));
        klineValues.push([element['开盘'], element['收盘'], element['最低'], element['最高']]);
        volumeValues.push(formatToHundredMillion(element['成交量'] || 0, '万', false));
    }
    return {
        categoryData,
        klineValues,
        volumeValues,
        stockCode: dataCopy?.[0]?.['股票代码']
    };
})
let chartInstance = null;
function calculateMA(dayCount) {
    var result = [];
    if (klineData.value.klineValues.length == 0) return;
    const len = klineData.value.klineValues.length;

    for (let i = 0; i < len; i++) {
        // 对于前dayCount-1个点，使用可用天数计算均线
        const availableDays = Math.min(i + 1, dayCount);
        var sum = 0;
        for (var j = 0; j < availableDays; j++) {
            sum += +klineData.value.klineValues[i - j][1];
        }
        result.push((sum / availableDays).toFixed(2));
    }

    return result;
}

const dataZoomStartWatch = watch(dataZoomStart, (newDataZoomStart, oldDataZoomStart) => {
    if (newDataZoomStart == 0 && oldDataZoomStart != 0 && klineData.value.klineValues.length > 40) {
        const { today, rangeDay } = getDateRange(120 + kLineDayAdd.value);
        getKlineData(rangeDay, today);
        kLineDayAdd.value += 10;
    }
})
const klineDataWatch = watch(klineData, (newKlineData, oldKlineData) => {
    console.log('newKlineData', newKlineData);
    console.log('oldKlineData', oldKlineData);
    const dataZoomEndComputed = newKlineData.stockCode === oldKlineData.stockCode ? dataZoomEnd.value >= 50 ? 50 : dataZoomEnd.value + 10 : 100
    if (chartInstance) {
        chartInstance.setOption({
            xAxis: [
                {
                    data: newKlineData.categoryData,
                    gridIndex: 0
                }, {
                    data: newKlineData.categoryData,
                    gridIndex: 1
                }
            ],
            series: [
                {
                    name: '日K',
                    type: 'candlestick',
                    data: newKlineData.klineValues,
                    xAxisIndex: 0,  // 使用第1个xAxis
                    yAxisIndex: 0,  // 使用第1个yAxis
                }, {
                    name: 'MA5',
                    type: 'line',
                    data: calculateMA(5),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: 'MA10',
                    type: 'line',
                    data: calculateMA(10),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: 'MA20',
                    type: 'line',
                    data: calculateMA(20),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: 'MA30',
                    type: 'line',
                    data: calculateMA(30),
                    smooth: true,
                    lineStyle: {
                        opacity: 0.5
                    }
                },
                {
                    name: '成交量', type: 'bar', data: newKlineData.volumeValues,
                    xAxisIndex: 1,  // 使用第二个xAxis
                    yAxisIndex: 1,  // 使用第二个yAxis
                },
            ],
            dataZoom: [
                {
                    type: 'inside',
                    start: 5,
                    end: dataZoomEndComputed,

                },
                {
                    type: 'slider',
                    start: 5,
                    end: dataZoomEndComputed,
                }
            ]
        });
    }
})
onMounted(() => {
    // 初始化图表
    chartInstance = echarts.init(chartRef.value);
    const upColor = '#ec0000';
    const upBorderColor = '#8A0000';
    const downColor = '#00da3c';
    const downBorderColor = '#008F28';
    // Each item: open，close，lowest，highest
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            // 添加formatter函数自定义提示内容
            formatter: function (params) {
                if (params && params.length > 0) {
                    let result = params[0].name + '<br/>';
                    params.forEach(param => {
                        if (param.seriesType === 'candlestick') {
                            result += '开盘价: ' + param.data[1] + '<br/>';
                            result += '收盘价: ' + param.data[2] + '<br/>';
                            result += '最低价: ' + param.data[3] + '<br/>';
                            result += '最高价: ' + param.data[4] + '<br/>';
                        } else if (param.seriesType === 'bar') {
                            result += '成交量: ' + param.value + '万手' + '<br/>';
                        } else {
                            result += param.seriesName + ': ' + param.value + '<br/>';
                        }
                    });
                    return result;
                }
                return '';
            }
        },
        legend: {
            data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30'],
            selectedMode: false
        },
        grid: [
            {
                left: '5%',
                right: '5%',
                // bottom: '30%',  // 为成交量图留出空间
                height: '65%'
            },
            {
                height: '15%',
                top: '78%',
                left: '5%',
                right: '5%',
                // bottom: '10%',
            }
        ],
        xAxis: [
            {
                type: 'category',
                data: klineData.value.categoryData,
                boundaryGap: 0.05,
                axisLine: { onZero: false },
                splitLine: { show: false },
                min: 'dataMin',
                max: 'dataMax',
                gridIndex: 0  // 对应第一个网格
            },
            {
                type: 'category',
                data: klineData.value.categoryData,
                boundaryGap: 0.05,
                axisLine: { show: false },
                axisTick: { show: false },
                splitLine: { show: false },
                axisLabel: { show: false },
                gridIndex: 1  // 对应第二个网格
            }
        ],
        yAxis: [
            {
                scale: true,
                splitArea: { show: true },
                gridIndex: 0,  // 对应第一个网格
                animationDuration: 300,
                animationEasing: 'quartOut'
            },
            {
                gridIndex: 1,  // 对应第二个网格
                axisLine: { show: false },
                axisTick: { show: false },
                splitLine: { show: false },
                animationDuration: 300,
                animationEasing: 'quartOut',
                axisLabel: {
                    formatter: '{value} 万'  // 添加成交量单位
                }
            }
        ],
        dataZoom: [
            {
                type: 'inside',
                start: 5,
                end: 100,
                xAxisIndex: [0, 1],
                zoomLock: false,  // 允许缩放
                moveOnMouseMove: true,  // 鼠标移动时移动视图
                moveOnMouseWheel: false,  // 鼠标滚轮时缩放，
                animation: true,
                animationDuration: 300,
                animationEasing: 'quartOut'
            },
            {
                show: true,
                type: 'slider',
                // top: '90%',
                start: 5,
                end: 100,
                xAxisIndex: [0, 1],
                handleSize: '100%',  // 滑块高度与dataZoom区域相同
                labelFormatter: '',  // 不显示标签
                animation: true,
                animationDuration: 300,
                animationEasing: 'quartOut'
            }
        ],
        series: [
            {
                name: '日K',
                type: 'candlestick',
                data: klineData.value.klineValues,
                xAxisIndex: 0,  // 使用第二个xAxis
                yAxisIndex: 0,  // 使用第二个yAxis
                animation: true,  // 添加动画
                animationDuration: 300,
                animationEasing: 'quartOut',
                itemStyle: {
                    color: upColor,
                    color0: downColor,
                    borderColor: upBorderColor,
                    borderColor0: downBorderColor
                },
                markPoint: {
                    label: {
                        formatter: function (param) {
                            return param != null ? Math.round(param.value) + '' : '';
                        }
                    },
                    data: [
                        {
                            name: 'Mark',
                            coord: ['2025/07/11', 9],
                            value: 9,
                            itemStyle: {
                                color: 'rgb(41,60,85)'
                            }
                        },
                        {
                            name: '最高价',
                            type: 'max',
                            valueDim: 'highest'  // 这里的'highest'对应最高价
                        },
                        {
                            name: '最低价',
                            type: 'min',
                            valueDim: 'lowest'   // 这里的'lowest'对应最低价
                        },
                        {
                            name: 'average value on close',
                            type: 'average',
                            valueDim: 'close'    // 这里的'close'对应收盘价
                        }
                    ],
                    tooltip: {
                        formatter: function (param) {
                            return param.name + '<br>' + (param.data.coord || '');
                        }
                    }
                },
                markLine: {
                    symbol: ['none', 'none'],
                    data: [
                        [
                            {
                                name: 'from lowest to highest',
                                type: 'min',
                                valueDim: 'lowest',
                                symbol: 'circle',
                                symbolSize: 10,
                                label: {
                                    show: false
                                },
                                emphasis: {
                                    label: {
                                        show: false
                                    }
                                }
                            },
                            {
                                type: 'max',
                                valueDim: 'highest',
                                symbol: 'circle',
                                symbolSize: 10,
                                label: {
                                    show: false
                                },
                                emphasis: {
                                    label: {
                                        show: false
                                    }
                                }
                            }
                        ],
                        {
                            name: 'min line on close',
                            type: 'min',
                            valueDim: 'close'
                        },
                        {
                            name: 'max line on close',
                            type: 'max',
                            valueDim: 'close'
                        }
                    ]
                }
            },
            // 在原有series数组末尾添加
            {
                name: '成交量',
                type: 'bar',
                xAxisIndex: 1,  // 使用第二个xAxis
                yAxisIndex: 1,  // 使用第二个yAxis
                data: klineData.value.volumeValues,
                animation: true,  // 添加动画
                animationDuration: 300,
                animationEasing: 'quartOut',
                itemStyle: {
                    // 根据K线涨跌设置成交量颜色
                    color: function (params) {
                        // 假设klineValues[params.dataIndex][1]是收盘价，[0]是开盘价
                        const close = klineData.value.klineValues[params.dataIndex][1];
                        const open = klineData.value.klineValues[params.dataIndex][0];
                        return close >= open ? upColor : downColor;
                    }
                }
            },
            {
                name: 'MA5',
                type: 'line',
                data: calculateMA(5),
                smooth: true,
                lineStyle: {
                    opacity: 0.5
                }
            },
            {
                name: 'MA10',
                type: 'line',
                data: calculateMA(10),
                smooth: true,
                lineStyle: {
                    opacity: 0.5
                }
            },
            {
                name: 'MA20',
                type: 'line',
                data: calculateMA(20),
                smooth: true,
                lineStyle: {
                    opacity: 0.5
                }
            },
            {
                name: 'MA30',
                type: 'line',
                data: calculateMA(30),
                smooth: true,
                lineStyle: {
                    opacity: 0.5
                }
            }
        ]
    };

    // 设置图表选项
    if (option && typeof option === 'object') {
        chartInstance.setOption(option);
    }

    chartInstance.on('datazoom', function (paramsNew) {
        if (paramsNew.start !== undefined) {
            dataZoomStart.value = paramsNew.start;
            dataZoomEnd.value = paramsNew.end;
        }
        if (paramsNew.batch) {
            dataZoomStart.value = paramsNew.batch[0].start;
            dataZoomEnd.value = paramsNew.batch[0].end;
        }

    });

    // 定义 resize 处理函数
    const handleResize = () => {
        chartInstance.resize();
    };

    // 添加事件监听
    window.addEventListener('resize', handleResize);

    // 存储到实例属性，方便卸载时访问
    chartInstance._handleResize = handleResize;
});
onUnmounted(() => {
    klineDataWatch();
    dataZoomStartWatch();
    chartInstance.dispose();
    window.removeEventListener('resize', chartInstance._handleResize);
})
</script>

<style scoped>
.echarts-container {
    width: 100%;
    flex: 1;
}
</style>